package com.bestcem.xm.survey.export.type;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.export.BaseTypeHandler;
import com.bestcem.xm.survey.grpc.client.dto.QstructsDto;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.bestcem.xm.survey.enums.QuestionTypeEnum.QUESTION_TYPE_GEO;

@Component
public class GeoHandler implements BaseTypeHandler {

    @Override
    public Map<String, String> getOpenColumnChangeDictV2(JSONObject data) {
        Map<String, String> res = new HashMap();
        res.put(getOpenRealcolV2(data, null, false), getOpenReadablecolV2(data, null, false));
        Integer info_level = (Integer) data.getOrDefault("info_level", 4);
        for (int i = 0; i < info_level; i++) {
            res.put(getOpenRealcolV2(data, i, false), getOpenReadablecolV2(data, i, false));
        }
        res.put(getOpenRealcolV2(data, null, true), getOpenReadablecolV2(data, null, true));
        return res;
    }

    private String getOpenRealcolV2(JSONObject data, Integer info_level, Boolean location) {
        String cid = data.getString("cid");
        if (Objects.nonNull(info_level)) {
            return Arrays.asList(cid + "__province", cid + "__city", cid + "__district", cid + "__street").get(info_level);
        }
        if (location) {
            return String.format("%s__coordinate", cid);
        }
        return cid;
    }


    private String getOpenReadablecolV2(JSONObject data, Integer info_level, Boolean location) {
        String title = BaseTypeHandler.clearHtml(data.getString("title"));
        if (Objects.nonNull(info_level)) {
            return Arrays.asList(title + "__省份", title + "__城市", title + "__区县", title + "__街道信息").get(info_level);
        }
        if (Objects.nonNull(location) && location) {
            return String.format("%s__经纬度", title);
        }
        return title;
    }

    @Override
    public List<String> getOpenColumnListV2(JSONObject data) {
        List<String> res = new ArrayList();
        res.add(getOpenRealcolV2(data, null, false));
        Integer info_level = (Integer) data.getOrDefault("info_level", 4);
        for (int i = 0; i < info_level; i++) {
            res.add(getOpenRealcolV2(data, i, false));
        }
        res.add(getOpenRealcolV2(data, null, true));
        return res;
    }


    @Override
    public Map<Object, Object> getOpenAnswerDictV2(JSONObject dataValue, Object answerValue) {
        JSONObject answers = (JSONObject) answerValue;
        Map<Object, Object> data = new HashMap<>();
        if (CollUtil.isEmpty(answers)) {
            data.put(getOpenRealcolV2(dataValue, null, false), null);
            Integer info_level = (Integer) dataValue.getOrDefault("info_level", 4);
            for (java.lang.Integer level = 0; level < info_level; level++) {
                data.put(getOpenRealcolV2(dataValue, null, true), null);
            }
        } else {
            Object city_answer = answers.getOrDefault("city", Collections.emptyMap());
            Map<Integer, String> new_city_answer = new HashMap();
            if (city_answer instanceof List) {
                int k = 1;
                for (String v : ((List<String>) city_answer)) {
                    new_city_answer.put(k, v);
                    k++;
                }
            } else {
                new_city_answer = (Map<Integer, String>) city_answer;
            }
            //直辖市，特别行政区 前端没有处理城市信息，需要后端补
            String privince1 = "", city1 = "";
            for (Map.Entry<Integer, String> entry : new_city_answer.entrySet()) {
                Integer index = entry.getKey();
                String answer = entry.getValue();
                if (index == 1) {
                    privince1 = answer;
                    break;
                }
            }
            //完整地址文本(省份-城市-区县-详细地址四级)
            StringBuilder full_address = new StringBuilder();
            StringBuilder finalFull_address_str = full_address;
            String finalPrivince = privince1;
            new_city_answer.forEach((index, answer) -> {
                //有省份，没有城市时，用省份代替
                if (index == 2 && StrUtil.isEmpty(answer) && StrUtil.isNotEmpty(finalPrivince)) {
                    answer = finalPrivince;
                }
                data.put(getOpenRealcolV2(dataValue, index - 1, false), answer);
                finalFull_address_str.append(answer);
            });
            String full_address_str = finalFull_address_str.toString();
            //完整的地理位置
            if (answers.containsKey("formattedAddress")) {
                full_address_str = (String) answers.get("formattedAddress");
            }
            data.put(getOpenRealcolV2(dataValue, null, false), full_address_str);
            //经纬度加入到普通列
            List coordinate_answer = (List) answers.get("coordinate");
            if (CollUtil.isNotEmpty(coordinate_answer)) {
                data.put(getOpenRealcolV2(dataValue, null, true), String.format("%s,%s", coordinate_answer.get(0), coordinate_answer.get(1)));
            } else {
                data.put(getOpenRealcolV2(dataValue, null, true), null);
            }
        }
        return data;
    }

    @Override
    public List<List<String>> getVarLabelsV2(JSONObject dataValue, boolean not01, boolean need_title) {
        List<List<String>> data = new ArrayList<>();
        List<String> var_list = new ArrayList(), val_list = new ArrayList();
        var_list.add(String.format("VARIABLE LABELS %s '地址'.", dataValue.getString("cid")));
        data.add(var_list);
        data.add(val_list);
        return data;
    }

    @Override
    public List<String> getSpssCodeV2(JSONObject param, QstructsDto qstruct) {
        List<String> head_list = new ArrayList<>();
        String cid = param.getString("cid");
        head_list.add(cid);
        head_list.add(String.format("%s__province", cid));
        head_list.add(String.format("%s__city", cid));
        head_list.add(String.format("%s__district", cid));
        head_list.add(String.format("%s__street", cid));
        head_list.add(String.format("%s__coordinate", cid));
        return head_list;
    }

    @Override
    public String getQuestionTypeValue() {
        return QUESTION_TYPE_GEO.getValue();
    }
}